package com.xiaomuwu.android

import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.xiaomuwu.android.ui.home.ContentFragment
import com.xiaomuwu.android.ui.Displayer
import com.xiaomuwu.android.ui.rele.ReleResFragment
import com.xiaomuwu.android.ui.rele.ReleUserFragment
import com.xiaomuwu.android.ui.LoginStatus
import com.xiaomuwu.android.ui.login.LoginFragment
import com.xiaomuwu.android.ui.MainViewModel
import com.xiaomuwu.android.ui.detail.ResDetailFragment
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.nav_header.*
import kotlinx.android.synthetic.main.res_list_fragment.*

class MainActivity : AppCompatActivity() {

    private val viewModel by lazy {
        ViewModelProviders.of(this).get(MainViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toobar)
        supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setHomeAsUpIndicator(R.drawable.ic_menu) // 设置导航图标
        }
        replaceFragment(ContentFragment())  // 显示首页

        // 为侧滑菜单引入header和menu
        navView.inflateHeaderView(R.layout.nav_header)
        navView.inflateMenu(R.menu.nav_menu)

        // 个人信息更新监听
        viewModel.personalLiveData.observe(this) { personalLiveData ->
            // check  为什么返回重进后下面三个都为空？第一次打开就不会？(在onCreate里调用时)
            userName?.text= personalLiveData.getOrNull()?.userName.toString()   // 更新用户名
            resCount?.text=personalLiveData.getOrNull()?.resCount.toString()    // 更新上传资料数
            fansCount?.text=personalLiveData.getOrNull()?.fansCount.toString()  // 更新粉丝数

            if (userName?.text == "null") {
                userName?.text = "未登录"
            }
            if (resCount?.text == "null") {
                resCount?.text = ""
            } else {
                resCount?.text = "上传 ${resCount.text}"
            }
            if (fansCount?.text == "null") {
                fansCount?.text = ""
            } else {
                fansCount?.text = "粉丝 ${fansCount.text}"
            }

//            // test
//            if (userName == null) {
//                Log.d("MainActivity","userName is null")
//            } else {
//                Log.d("MainActivity","userName is not null")
//            }
//            if (resCount == null) {
//                Log.d("MainActivity","resCount is null")
//            } else {
//                Log.d("MainActivity","resCount is not null")
//            }
//            if (fansCount == null) {
//                Log.d("MainActivity","fansCount is null")
//            } else {
//                Log.d("MainActivity","fansCount is not null")
//            }
        }

        // 菜单项点击监听
        navView.setNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.navHome -> {
                    // 切换至首页
                    Displayer.pprevPageStatus = Displayer.prevPageStatus
                    Displayer.prevPageStatus = Displayer.pageStatus
                    Displayer.pageStatus = "Home"
//                    ForSearch.init()    //check(为什么和下一行换位置后没影响？)
                    replaceFragment(ContentFragment())
                    drawerLayout.closeDrawers() // 关闭菜单
                }
                R.id.navFavorites -> {
                    if (LoginStatus.user_ID != null) {
                        // 切换至相关资料页
                        Displayer.pprevPageStatus = Displayer.prevPageStatus
                        Displayer.prevPageStatus = Displayer.pageStatus
                        Displayer.pageStatus = "Favorites"
                        replaceFragment(ReleResFragment())
                        drawerLayout.closeDrawers() // 关闭菜单
                    } else {
                        Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show()
                    }
                }
                R.id.navUpload -> {
                    if (LoginStatus.user_ID != null) {
                        // 切换至相关资料页
                        Displayer.pprevPageStatus = Displayer.prevPageStatus
                        Displayer.prevPageStatus = Displayer.pageStatus
                        Displayer.pageStatus = "Upload"
                        replaceFragment(ReleResFragment())
                        drawerLayout.closeDrawers() // 关闭菜单
                    } else {
                        Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show()
                    }
                }
                R.id.navFollow -> {
                    if (LoginStatus.user_ID != null) {
                        // 切换至相关用户页
                        Displayer.pprevPageStatus = Displayer.prevPageStatus
                        Displayer.prevPageStatus = Displayer.pageStatus
                        Displayer.pageStatus = "Follow"
                        replaceFragment(ReleUserFragment())
                        drawerLayout.closeDrawers() // 关闭菜单
                    } else {
                        Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show()
                    }
                }
                R.id.navFans -> {
                    if (LoginStatus.user_ID != null) {
                        // 切换至相关用户页
                        Displayer.pprevPageStatus = Displayer.prevPageStatus
                        Displayer.prevPageStatus = Displayer.pageStatus
                        Displayer.pageStatus = "Fans"
                        replaceFragment(ReleUserFragment())
                        drawerLayout.closeDrawers() // 关闭菜单
                    } else {
                        Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show()
                    }
                }
                R.id.navLogIn -> {
                    // 切换至登录页
                    Displayer.pprevPageStatus = Displayer.prevPageStatus
                    Displayer.prevPageStatus = Displayer.pageStatus
                    Displayer.pageStatus = "Login"
                    replaceFragment(LoginFragment())
                    drawerLayout.closeDrawers() // 关闭菜单
                }
                R.id.navLogOut -> {
                    if (LoginStatus.user_ID != null) {
                        // 切换至首页
                        Displayer.pprevPageStatus = Displayer.prevPageStatus
                        Displayer.prevPageStatus = Displayer.pageStatus
                        Displayer.pageStatus = "Home"
                        replaceFragment(ContentFragment())
                        LoginStatus.user_ID = null  // 重置用户ID
                        LoginStatus.passWord = null // 重置用户密码
                        drawerLayout.closeDrawers() // 关闭菜单
                    } else {
                        Toast.makeText(this, "未登录", Toast.LENGTH_SHORT).show()
                    }
                }
            }
            true
        }

        val navHeaderView = navView.getHeaderView(0)    // 获取菜单头部布局

        // 用户名点击监听
        val userName = navHeaderView.findViewById<TextView>(R.id.userName)
        userName?.setOnClickListener {
            if (LoginStatus.user_ID == null) {
                Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show()
            } else {
                // 切换至登录页（修改用户信息）
                Displayer.pprevPageStatus=Displayer.prevPageStatus
                Displayer.prevPageStatus=Displayer.pageStatus
                Displayer.pageStatus = "ModifyUser"
                replaceFragment(LoginFragment())
                drawerLayout.closeDrawers() // 关闭菜单
            }
        }

        // 菜单监听
        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {

            override fun onDrawerStateChanged(newState: Int) {}

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            // 打开菜单监听
            override fun onDrawerOpened(drawerView: View) {
                hideKeyboard()  // 收起键盘
                updatePersonal()    // 更新个人信息
            }

            override fun onDrawerClosed(drawerView: View) {}

        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            // Home按钮点击监听
            android.R.id.home -> drawerLayout.openDrawer(GravityCompat.START)   // 打开菜单
        }
        return true
    }

    // 返回键点击监听
    override fun onBackPressed() {
        // 根据页面执行相关操作
        if (Displayer.pageStatus == "Home") {
            super.onBackPressed()
        } else {
            if (Displayer.pageStatus == "ResDetail" || Displayer.pageStatus == "UserDetail" ||
                Displayer.pageStatus=="WebPage" || Displayer.pageStatus == "UploadRes" ||
                Displayer.pageStatus == "ModifyRes") {
                // 切换页面
                when (Displayer.prevPageStatus) {
                    "Home" -> {
                        // 切换至首页
                        Displayer.pprevPageStatus=Displayer.prevPageStatus
                        Displayer.prevPageStatus=Displayer.pageStatus
                        Displayer.pageStatus="Home"
                        replaceFragment(ContentFragment())
                    }
                    "Favorites" -> {
                        // 切换至相关资料业
                        Displayer.pprevPageStatus=Displayer.prevPageStatus
                        Displayer.prevPageStatus=Displayer.pageStatus
                        Displayer.pageStatus="Favorites"
                        replaceFragment(ReleResFragment())
                    }
                    "Upload" -> {
                        // 切换至相关资料页
                        Displayer.pprevPageStatus=Displayer.prevPageStatus
                        Displayer.prevPageStatus=Displayer.pageStatus
                        Displayer.pageStatus="Upload"
                        replaceFragment(ReleResFragment())
                    }
                    "Follow" -> {
                        // 切换至相关用户页
                        Displayer.pprevPageStatus=Displayer.prevPageStatus
                        Displayer.prevPageStatus=Displayer.pageStatus
                        Displayer.pageStatus="Follow"
                        replaceFragment(ReleUserFragment())
                    }
                    "Fans" -> {
                        // 切换至相关用户页
                        Displayer.pprevPageStatus=Displayer.prevPageStatus
                        Displayer.prevPageStatus=Displayer.pageStatus
                        Displayer.pageStatus="Fans"
                        replaceFragment(ReleUserFragment())
                    }
                    "ResDetail" -> {
                        // 切换至资料详情页
                        Displayer.prevPageStatus=Displayer.pprevPageStatus
                        Displayer.pprevPageStatus=Displayer.pageStatus
                        Displayer.pageStatus="ResDetail"
                        replaceFragment(ResDetailFragment())
                    }
                }
            } else {
                // 切换至首页
                Displayer.pprevPageStatus=Displayer.prevPageStatus
                Displayer.prevPageStatus=Displayer.pageStatus
                Displayer.pageStatus="Home"
                replaceFragment(ContentFragment())
            }
        }
    }

    /**
     * 切换页面函数
     */
    fun replaceFragment(fragment: Fragment){
        val fragmentManager=supportFragmentManager
        val transaction=fragmentManager.beginTransaction()
        transaction.replace(R.id.contentLayout, fragment)
        transaction.commit()
    }

    /**
     * 更新个人信息函数
     */
    fun updatePersonal(){
        viewModel.getPersonalLiveData(LoginStatus.user_ID)
    }

    /**
     * 收起键盘函数
     */
    fun hideKeyboard(){
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
    }

}